package org.smart4j.framework.helper;


import org.apache.commons.lang.ArrayUtils;
import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.utils.ReflectionUtil;

import java.lang.annotation.Inherited;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * Created by Wenxin on 2017/2/25.
 */
public class IocHelper {

    static {
//        获取所有bean
        Map<Class<?>,Object> beanMap = BeanHelper.getBeanMap();
//        遍历bean
        for (Map.Entry<Class<?>,Object> beanEntry:beanMap.entrySet()){
//            获取类
            Class<?> cls = beanEntry.getKey();
//            获取实例
            Object obj = beanEntry.getValue();
//            获取所有类属性
            Field[] fields = cls.getDeclaredFields();
            if (ArrayUtils.isNotEmpty(fields)){
                for (Field field:fields){
//                    是否有Inject注解
                    if (field.isAnnotationPresent(Inject.class)){
                        Class<?> fieldType = field.getType();
                        Object beanFieldInstance = beanMap.get(fieldType);
                        if (beanFieldInstance != null){
//                            注入属性
                            ReflectionUtil.setField(obj,field,beanFieldInstance);
                        }
                    }
                }
            }
        }
    }

}
